package com.jyw.framework.web.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jyw.common.core.domain.entity.SysRole;
import com.jyw.common.core.domain.entity.SysUser;
import com.jyw.common.core.domain.model.LoginUser;
import com.jyw.common.core.domain.model.MpLoginUserBinding;
import com.jyw.common.enums.UserStatus;
import com.jyw.common.exception.ServiceException;
import com.jyw.custom.sms.service.ISmsService;
import com.jyw.system.domain.SysUserDept;
import com.jyw.system.domain.SysUserDeptRole;
import com.jyw.system.mapper.SysRoleMapper;
import com.jyw.system.service.ISysRoleService;
import com.jyw.system.service.ISysUserDeptRoleService;
import com.jyw.system.service.ISysUserDeptService;
import com.jyw.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 沈峻
 * @ClassName WechatDetailsService
 * @Description 微信登录验证处理
 * @Date 2023/9/5 16:25
 **/
@Service
@Slf4j
public class WechatDetailsService implements UserDetailsService {

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysUserDeptRoleService userDeptRoleService;

    @Resource
    private ISmsService smsService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private ISysUserDeptService userDeptService;

    @Resource
    private SysRoleMapper roleMapper;


//    @Override
//    public UserDetails loadUserByUsername(String phonenumber) throws UsernameNotFoundException {
//        SysUser user = userService.lambdaQuery().eq(SysUser::getPhonenumber, phonenumber).one();
//        if(ObjectUtils.isEmpty(user)){
//            log.info("用户不存在");
//            throw new ServiceException("登录手机号:"+phonenumber+"不存在");
//        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
//            log.info("登录用户:{}已被删除",phonenumber);
//            throw new ServiceException("对不起,您的账号:"+phonenumber+"已被删除");
//        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
//            log.info("登录用户:{},已被停用",phonenumber);
//            throw new ServiceException("对不起,您的账号:"+phonenumber+"已停用");
//        }
//
//        SysUserDeptRole userDeptRole = userDeptRoleService.getUserDefault(user.getUserId());
//        if(ObjectUtils.isEmpty(userDeptRole)){
//            log.info("登录用户:{},没有默认角色");
//            throw new ServiceException("对不起,您的账号:"+phonenumber+"没有默认角色");
//        }
//        return new LoginUser(user.getUserId(), userDeptRole.getDeptId(),userDeptRole.getRoleId(),userDeptRole.getId(), user, Sets.newHashSet("*:*:*"));
//    }

    public UserDetails loadUserByBody(MpLoginUserBinding bind) {
        SysUser user = null;
        if((!ObjectUtils.isEmpty(bind.getKey())||!ObjectUtils.isEmpty(bind.getSmsCode()))&&!ObjectUtils.isEmpty(bind.getPhone())){
            //绑定用户,验证短信
            if (!smsService.validateCode(bind.getKey(), bind.getSmsCode())) {
                throw new ServiceException("验证码错误");
            }
            //通过电话获取用户
            user = userService.lambdaQuery().eq(SysUser::getPhonenumber, bind.getPhone()).one();
            //如果用户不为空那么将code与用户绑定
            if(!ObjectUtils.isEmpty(user)){
                userService.lambdaUpdate().eq(SysUser::getUserId,user.getUserId()).set(SysUser::getOpenid,bind.getOpenid()).update();
            }
        }else{
            user = userService.lambdaQuery().eq(SysUser::getOpenid, bind.getOpenid()).one();
        }
        if(ObjectUtils.isEmpty(user)){
            log.info("用户不存在");
            throw new ServiceException("用户不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户,已被删除");
            throw new ServiceException("对不起,您的账号已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户:,已被停用");
            throw new ServiceException("对不起,您的账号已停用");
        }

        List<SysRole> sysUserRoleList = roleMapper.selectRolePermissionByUserId(user.getUserId());
        if(CollectionUtils.isEmpty(sysUserRoleList)){
            log.info("您的账号,未分配权限.");
            throw new ServiceException("对不起，您的账号未分配角色");
        }

        //查询用户默认部门
        SysUserDept userDept = userDeptService.lambdaQuery().eq(SysUserDept::getIsDefault, 1).eq(SysUserDept::getUserId, user.getUserId()).one();
        if(ObjectUtils.isEmpty(userDept)){
            throw new ServiceException("用户没有默认部门");
        }

        //给用户设置归属部门
        user.setDeptIdList(userService.getUserDeptIds(user.getUserId()));
        return createLoginUser(user,userDept,sysUserRoleList);
    }

    public UserDetails createLoginUser(SysUser user, SysUserDept userDept, List<SysRole> sysRoleList)
    {
        return new LoginUser(user.getUserId(), userDept.getDeptId(),user,sysRoleList, Sets.newHashSet("*:*:*"));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return null;
    }
}
